<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">要单管理系统</div>
    <div class="login-form-sub-title">琉璃工房</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      @submit="handleSubmit"
    >
      <a-form-item
        field="username"
        :rules="[{ required: true, message: '用户名不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="userInfo.username" placeholder="请输入用户名">
          <template #prefix>
            <icon-user />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        field="password"
        :rules="[{ required: true, message: '密码不能为空' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.password"
          placeholder="请输入密码"
          allow-clear
        >
          <template #prefix>
            <icon-lock />
          </template>
        </a-input-password>
      </a-form-item>
      <a-row>
        <a-col :span="14">
          <a-form-item
            field="validateCode"
            :rules="[{ required: true, message: '验证码不能为空' }]"
            :validate-trigger="['change', 'blur']"
            hide-label
          >
            <a-input
              v-model="userInfo.validateCode"
              placeholder="请输入验证码"
            />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item field="pica" hide-label>
            <img
              class="w-full"
              :src="userInfo.picPath"
              style="padding-left: 5px"
              alt="验证码生成失败"
              @click="resetCaptcha"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-space :size="16" direction="vertical">
        <a-button type="primary" html-type="submit" long :loading="loading">
          登录
        </a-button>
      </a-space>
    </a-form>
  </div>
  <a-modal
    v-model:visible="confirmVisible"
    ok-text="立即修改"
    :mask-closable="false"
    :hide-cancel="true"
    :closable="false"
    :esc-to-close="false"
    @ok="handleOk"
  >
    <template #title> 安全提示 </template>
    <div>您的密码已过期，请重置！</div>
  </a-modal>
  <a-modal
    v-model:visible="passwordVisible"
    title="重置密码"
    :mask-closable="false"
    :closable="true"
    @ok="handleEdit"
    @before-ok="handleBeforeOk"
  >
    <a-form ref="formRef" :model="editFormModel">
      <a-form-item
        field="oldPassWord"
        label="原密码"
        :rules="[{ required: true, message: '请输入原密码' }]"
        :validate-trigger="['change', 'blur']"
        val
      >
        <a-input-password
          v-model="editFormModel.oldPassWord"
          placeholder="请输入"
          allow-clear
        >
        </a-input-password>
      </a-form-item>
      <a-form-item
        field="passWord"
        label="新密码"
        :rules="passWordRules"
        :validate-trigger="['change', 'blur']"
        val
      >
        <a-input-password
          v-model="editFormModel.passWord"
          placeholder="新密码至少8个字符"
          allow-clear
        >
        </a-input-password>
      </a-form-item>
      <a-form-item
        field="againPassword"
        label="再次密码"
        :rules="againPassWordRules"
        :validate-trigger="['change', 'blur']"
        val
      >
        <a-input-password
          v-model="editFormModel.againPassword"
          placeholder="再次密码至少8个字符"
          allow-clear
        >
        </a-input-password>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import type { LoginData } from '@/api/user';
  import { FormInstance } from '@arco-design/web-vue/es/form';

  const router = useRouter();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();
  const confirmVisible = ref(false);
  const passwordVisible = ref(false);
  const formRef = ref<FormInstance>();

  const userInfo = reactive({
    username: '',
    password: '',
    validateCode: '',
    picPath: '',
    captchaCode: '',
  });

  const editFormModel = reactive({
    oldPassWord: '',
    passWord: '',
    againPassword: '',
  });

  const resetCaptcha = async () => {
    const { data } = await userStore.captcha();
    userInfo.captchaCode = data.captchaCode;
    userInfo.picPath = data.image;
  };

  onMounted(() => {
    resetCaptcha();
  });

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (!errors) {
      setLoading(true);
      try {
        const res = await userStore.login(values as LoginData);
        if (res.status === 200) {
          window.localStorage.setItem('userRole', res.data.access);
          if (res.data.forcePassWord === 1) {
            confirmVisible.value = true;
          } else {
            await router.push({ name: 'Workplace' });
            Message.success('登录成功，欢迎使用');
          }
        } else {
          await resetCaptcha();
          Message.error(res.statusText);
        }
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };

  const handleOk = () => {
    confirmVisible.value = false;
    passwordVisible.value = true;
  };

  const passWordRules = [
    {
      validator: (value: string, cb: any) => {
        if (
          !/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&^()_-])[A-Za-z\d$@$!%*#?&^()_-]{8,}$/.test(
            value
          )
        ) {
          cb('至少8个字符，至少1个字母，1个数字和1个特殊字符!');
        }
      },
      required: true,
    },
  ];

  const againPassWordRules = [
    {
      validator: (value: string, cb: any) => {
        if (value === '') {
          cb('请输入确认密码');
        } else if (value !== editFormModel.passWord) {
          cb('确认密码与密码不一致');
        }
      },
      required: true,
    },
  ];

  const handleBeforeOk = (done: (closed: boolean) => void) => {
    if (formRef.value) {
      formRef.value
        .validate()
        .then((res) => done(!res))
        .catch(error => done(false));
    } else {
      done(true);
    }
  };

  const handleEdit = async () => {
    const rep = await userStore.changePassword(editFormModel);
    if (rep.status === 200) {
      Message.success(rep.statusText);
      await router.push({ name: 'Workplace' });
    } else {
      passwordVisible.value = true;
    }
  };
</script>

<style lang="less" scoped>
  .login-form {
    &-wrapper {
      width: 320px;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
